package tests;

import static org.junit.Assert.assertEquals;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.BeforeClass;
import org.junit.Test;

import pdf.SciPDF;

public class PDFTests {

	static final String manuallyRecognizedDir = "D:\\Work\\Misc\\Vernad\\Test\\recognized\\";
	static final String testPdfsDir = "D:\\Work\\Misc\\Vernad\\Test\\pdf\\";
	
	static List<TestCasePair> testCasePairs = new ArrayList<TestCasePair>();
	
	static void LoadTestPDFs() throws Exception {
		
		for (TestCasePair tcp : testCasePairs) {
			String path = testPdfsDir + tcp.recognized.get("file").trim() + ".pdf";
			tcp.pdf = new SciPDF(path);	
		}
	}
	
	static void LoadRecognized() throws Exception {
		
		testCasePairs.clear();
		
		File dir = new File(manuallyRecognizedDir);
		File[] files = dir.listFiles();
		
		for (File f : files) {
			
			Map<String, String> map = new HashMap<String, String>();
			
			FileInputStream fstream = new FileInputStream(f.getAbsolutePath());
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			  
			String key = "";
			StringBuilder valueBuilder = new StringBuilder();
			
			String line;
			while ((line = br.readLine()) != null)   {
				if (line.startsWith("[") && line.endsWith("]")) {
					
					if (!key.isEmpty()) {
						map.put(key, valueBuilder.toString());
						
						key = "";
						valueBuilder = new StringBuilder();
					}
					
					key = line.substring(1, line.length() - 1).toLowerCase();
				} else {
					valueBuilder.append(line);
					valueBuilder.append(System.getProperty("line.separator"));
				}
			}
			
			if (!key.isEmpty()) {
				map.put(key, valueBuilder.toString());
			}
			
			testCasePairs.add(new TestCasePair(null, map));
			  
			in.close();
		}
	}
	
	@BeforeClass
	public static void setUp() throws Exception {
		
		LoadRecognized();
		LoadTestPDFs();
	}

	@Test
	public void testGetTitle() {
		
		for (TestCasePair tcp : testCasePairs) {
			
			String actual = tcp.pdf.getTitle().trim();
			String expected = tcp.recognized.get("title").trim().toUpperCase();
			
			assertEquals("Title failed on file #" + tcp.recognized.get("file"), expected, actual);
		}
	}
	
	@Test
	public void testGetUDK() {
		
		for (TestCasePair tcp : testCasePairs) {
			
			String actual = tcp.pdf.getUDK().trim();
			String expected = tcp.recognized.get("UDK").trim().toUpperCase();
			
			assertEquals("UDK failed on file #" + tcp.recognized.get("file"), expected, actual);
		}
	}
}
